# -*- coding: UTF-8 -*-
import random

import requests

from utils.log_util.LoggerUtil import get_logger

log = get_logger(__name__)

# requests 重试次数
requests_retry_times = 5

# 定义伪装的headers
headers_1 = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3" + str(
        random.randint(10, 99)) + "7.100 Safari/537.36" + str(random.randint(10, 99))
}
headers_2 = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3" + str(
        random.randint(10, 99)) + "7.100 Safari/537.36" + str(random.randint(10, 99))
}
headers_3 = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/6" + str(
        random.randint(1, 9)) + ".0.3" + str(random.randint(10, 99)) + "2.140 Safari/537.36 Edge/17.171" + str(
        random.randint(10, 99))
}

# 定义代理链接
proxy_1 = {
    "http": "http://111.7.130.101:8080",
    "https": "http://111.7.130.101:8080",
}
proxy_2 = {
    "http": "http://39.137.69.10:8080",
    "https": "http://39.137.69.10:8080",
}
proxy_3 = {
    "http": "http://39.137.77.66:8080",
    "https": "http://39.137.77.66:8080",
}


# 快速切换Headers User-Agent
def switchHeaders():
    """
    快速切换Headers User-Agent
    headers定义在Constants中
    """
    n = random.randint(1, 3)
    switch = {
        1: headers_1,
        2: headers_2,
        3: headers_3,
    }
    headers = switch[n]

    log.debug("使用的User-Agent: " + headers["User-Agent"])

    return headers


# 快速切换服务器代理
# Attention: 定义的服务器代理为免费代理，稳定性比较差，谨慎使用
def switchProxy():
    """
    快速切换服务器代理
    proxy定义在Constants中
    Attention: 定义的服务器代理为免费代理，稳定性比较差，谨慎使用
    """
    n = random.randint(1, 3)
    switch = {
        1: proxy_1,
        2: proxy_2,
        3: proxy_3,
    }
    proxy = switch[n]
    return proxy


# 获取request对象
def getRequest(url):
    """
    获取request对象
    :param url: 需要请求的url
    :return: request对象
    """
    requests.adapters.DEFAULT_RETRIES = requests_retry_times
    s = requests.session()
    s.keep_alive = False
    s = requests.get(url, headers=switchHeaders())

    log.debug("def [getRequest] is called. URL is %s " % url)
    return s


# 获取post request对象
def postRequest(url, requestBody):
    """
    获取post request对象
    :param url: 需要请求的url
    :param requestBody 请求值
    :return: post request对象
    """
    requests.adapters.DEFAULT_RETRIES = requests_retry_times
    s = requests.session()
    s.keep_alive = False
    result = requests.post(url, data=requestBody, headers=switchHeaders())

    log.debug("def [getPostRequest] is called. URL is %s, requestBody is %s " % (url, requestBody))
    return result


# 使用代理获取request对象
def getRequestByProxy(url):
    """
    使用代理获取request对象
    :param 需要请求的url
    :return: request对象
    """
    request = requests.get(url, headers=switchHeaders(), proxies=switchProxy())
    return request